<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>碰撞变色</title>
	<style type="text/css">
	body{
		position: relative;
	}
	#box{
		width: 50px;
		height: 50px;
		background-color: yellow;
		position: absolute;

		}
	#fixed{
		width: 100px;
		height: 100px;
		background-color: rgba(99,99,99,0.3);
		position: absolute;
		top: 300px;
		left: 300px;
	}
	</style>
</head>
<body>
	<div id="box"></div>
	<div id="fixed"></div>
</body>
	<script type="text/javascript">
	//获取元素
	var box = document.getElementById('box');
	var fix = document.getElementById('fixed');
	//获取大小盒子宽高，左右边距
	var minw = box.offsetWidth;
	var minh = box.offsetHeight;

	var maxw = fix.offsetWidth;
	var maxh = fix.offsetHeight;

	var maxt = fix.offsetTop;
	var maxl = fix.offsetLeft;
	//计算差值
	var mtt = maxt - minh ;
	var mtb = maxt + maxh ;
	var mle = maxl - minw ;
	var mri = maxl + maxw ;

	//函数使运动
	box.onmousedown = function(event){
		
		//计算鼠标在盒子里的宽高位置
		var a = event.clientX-box.offsetLeft;
		var b = event.clientY-box.offsetTop;

		//鼠标移动计算盒子距离body位置
		document.onmousemove = function(event){
		   box.style.left = (event.clientX-a)+'px';
		   box.style.top = (event.clientY-b)+'px';

		   //if语句判断接触，大盒子改变颜色
		 	if((event.clientY-b)>mtt && (event.clientY-b)<mtb && (event.clientX-a)>mle && (event.clientX-a)<mri){
		 		fix.style.backgroundColor = 'red';
		 	}else{
		 		fix.style.backgroundColor = 'rgba(99,99,99,0.3)';
		 	} 
		}
	}
	//鼠标抬起小盒子停止运动
    document.onmouseup = function(){
	 document.onmousemove = '';
 }





	</script>
</html>